<template>
  <div class="score-inquiry">
    <div class="header">
      <h2>成绩查询</h2>
      <div class="search-box">
        <el-input
          v-model="searchText"
          placeholder="搜索考试名称"
          class="search-input"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="refreshList"><el-icon><Refresh /></el-icon></el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredScoreList"
      border
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="examName" label="考试名称" min-width="180" />
      <el-table-column prop="subject" label="科目" width="120" />
      <el-table-column prop="score" label="得分" width="100">
        <template #default="{ row }">
          <span :class="{ 'pass': row.score >= 60, 'fail': row.score < 60 }">
            {{ row.score }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="totalScore" label="总分" width="100" />
      <el-table-column prop="submitTime" label="提交时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.submitTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.score >= 60 ? 'success' : 'danger'">
            {{ row.score >= 60 ? '及格' : '不及格' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="correctRate" label="正确率" width="100">
        <template #default="{ row }">
          <el-progress 
            :percentage="Math.round((row.score / row.totalScore) * 100)" 
            :color="getProgressColor(Math.round((row.score / row.totalScore) * 100))"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button 
            link 
            type="primary" 
            @click="viewDetail(row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="total > 0"
      class="pagination"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      background
    />

    <!-- 成绩详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="成绩详情"
      width="60%"
      destroy-on-close
    >
      <div v-if="currentExam" class="exam-detail">
        <div class="basic-info">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="考试名称">{{ currentExam.examName }}</el-descriptions-item>
            <el-descriptions-item label="科目">{{ currentExam.subject }}</el-descriptions-item>
            <el-descriptions-item label="客观题得分">{{ currentExam.objectiveScore }}</el-descriptions-item>
            <el-descriptions-item label="主观题得分">{{ currentExam.subjectiveScore }}</el-descriptions-item>
            <el-descriptions-item label="总分">{{ currentExam.totalScore }}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{ formatDateTime(currentExam.submitTime) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="answer-analysis" v-if="currentExam.questions">
          <h3>试题分析</h3>
          <div v-for="(question, index) in currentExam.questions" :key="index" class="question-item">
            <div class="question-header">
              <span class="question-number">第 {{ index + 1 }} 题</span>
              <span class="question-type">{{ question.type }}</span>
              <span class="question-score">得分：{{ question.score }}</span>
              <el-tag :type="question.correctness === '正确' ? 'success' : 'danger'" size="small">
                {{ question.correctness }}
              </el-tag>
            </div>
            <div class="question-content">{{ question.content }}</div>
            <div class="answer-info">
              <p>您的答案：{{ question.studentAnswer }}</p>
              <p>正确答案：{{ question.correctAnswer }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import examApi from '@/api/exam'
import { useUser } from '@/stores/userInfo'
import dayjs from 'dayjs'

const userStore = useUser()

// 数据
const loading = ref(false)
const searchText = ref('')
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const detailDialogVisible = ref(false)
const currentExam = ref(null)
const scoreList = ref([])

// 过滤后的成绩列表
const filteredScoreList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  let filtered = scoreList.value
  
  if (searchText.value) {
    filtered = scoreList.value.filter(item => 
      item.examName && item.examName.toLowerCase().includes(searchText.value.toLowerCase()) ||
      item.subject && item.subject.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }
  
  total.value = filtered.length
  return filtered.slice(start, end)
})

// 获取已作答考试列表
const fetchAnsweredExams = async () => {
  loading.value = true
  try {
    const schoolNumber = userStore.userInfo.schoolNumber
    const res = await examApi.studentGradeInquiry(schoolNumber)
    if (res.code === 200) {
      // 处理接口返回的数据
      scoreList.value = res.data.map(item => {
        return {
          examId: item.examId,
          examName: item.examName,
          subject: item.subject,
          score: Number(item.score) || 0,
          totalScore: Number(item.totalScore) || 100,
          submitTime: item.submitTime
        }
      })
      total.value = scoreList.value.length
    } else {
      ElMessage.warning(res.message || '暂无已作答考试')
      scoreList.value = []
    }
  } catch (error) {
    console.error('获取已作答考试列表失败:', error)
    ElMessage.error('获取已作答考试列表失败')
    scoreList.value = []
  } finally {
    loading.value = false
  }
}

// 查看详情
const viewDetail = async (row) => {
  loading.value = true
  try {
    const schoolNumber = userStore.userInfo.schoolNumber
    const res = await examApi.studentResultsForDetails(row.examId, schoolNumber)
    if (res.code === 200) {
      currentExam.value = {
        examName: res.data.examName,
        subject: res.data.subject,
        score: res.data.totalScore,
        objectiveScore: res.data.objectiveScore,
        subjectiveScore: res.data.subjectiveScore,
        totalScore: 100,
        submitTime: res.data.submitTime,
        questions: res.data.examAndAnswerlist.map(item => ({
          questionId: item.questionId,
          content: item.content,
          type: item.type,
          studentAnswer: item.studentAnswer,
          correctAnswer: item.correctAnswer,
          score: item.score,
          correctness: item.correctness
        }))
      }
      detailDialogVisible.value = true
    } else {
      ElMessage.warning(res.message || '获取详情失败')
    }
  } catch (error) {
    console.error('获取考试详情失败:', error)
    ElMessage.error('获取考试详情失败')
  } finally {
    loading.value = false
  }
}

// 搜索功能
const handleSearch = () => {
  currentPage.value = 1
}

// 刷新列表
const refreshList = () => {
  searchText.value = ''
  currentPage.value = 1
  fetchAnsweredExams()
}

// 分页功能
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 格式化日期时间
const formatDateTime = (time) => {
  if (!time) return '-'
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 60) {
    return '#F56C6C'
  } else if (percentage < 80) {
    return '#E6A23C'
  } else {
    return '#67C23A'
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchAnsweredExams()
})
</script>

<style lang="scss" scoped>
.score-inquiry {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      color: #303133;
    }

    .search-box {
      display: flex;
      gap: 10px;
      
      .search-input {
        width: 300px;
      }
    }
  }

  .pass {
    color: #67c23a;
    font-weight: bold;
  }

  .fail {
    color: #f56c6c;
    font-weight: bold;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.exam-detail {
  padding: 20px;

  .basic-info {
    margin-bottom: 30px;

    h3 {
      margin-bottom: 20px;
      color: #303133;
    }
  }

  .answer-analysis {
    h3 {
      margin-bottom: 20px;
      color: #303133;
    }

    .question-item {
      margin-bottom: 20px;
      padding: 15px;
      border: 1px solid #ebeef5;
      border-radius: 4px;

      .question-header {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 10px;

        .question-number {
          font-weight: bold;
          color: #303133;
        }

        .question-type {
          color: #409eff;
        }

        .question-score {
          color: #67c23a;
        }
      }

      .question-content {
        margin-bottom: 10px;
        color: #606266;
      }

      .answer-info {
        p {
          margin: 5px 0;
          color: #606266;

          &:first-child {
            color: #e6a23c;
          }

          &:last-child {
            color: #67c23a;
          }
        }
      }
    }
  }
}
</style>